﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Filters;

/// <summary>
/// 验证码验证
/// </summary>
public class GeetAttribute : Attribute, IAsyncActionFilter
{

    /// <summary>
    /// 验证码
    /// </summary>
    /// <param name="context"></param>
    /// <param name="next"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        var header = context.HttpContext.Request.Headers;

        string challenge = header["challenge"].ToString() ?? "0";

        string validate = header["validate"].ToString() ?? "0";

        string seccode = header["seccode"].ToString() ?? "0";

        bool validState = await new GeetestOpenApi().SecondValidate(challenge, validate, seccode);

        if (!validState)
        {
            context.Result = new JsonResult(new { code = 4001, msg = "验证码验证失败", state = false });

            return;
        }

        await next();
    }
}
